﻿using Crm.Infrastructure.IOC;
using Crm.Service.Instance;
using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Request.Org;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.Dto.Response.Customer;
using CRM.Infrastructure.Dto.Response.Dictionary;
using CRM.Infrastructure.Dto.Response.Login;
using CRM.Infrastructure.Dto.Response.Org;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.IOC;
using CRM.Infrastructure.Tools;
using CRM.Service.EFCore;
using CRM.Service.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace CRM.Service.Instance
{
    [Inject_]
    public class Org_Service : Base_Service, I_Org_Service
    {
        private readonly Org_IOC _org_IOC;
        private readonly Login_IOC _login_IOC;

        public Org_Service(Org_IOC org_IOC, Login_IOC login_IOC)
        {
            _org_IOC = org_IOC;
            _login_IOC = login_IOC;

        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Depts(Org_Request_Dto dto)
        {
            var depts = _org_IOC._sys_department_EFCore.QueryAll(d =>
              (dto.isBan == -1 || d.DIsBan == dto.isBan)).ToList();
            var root = depts.Where(d => d.DParent == null).ToList();
            //获取各个部门的人数
            var users = _login_IOC._sys_User_EFCore.QueryAll(d => d.UDept != null).ToList();
            var data = root.Select(d => new Department_Response_Dto
            {
                id = d.DId,
                count = users.Count(e => e.UDept == d.DId),
                explain = d.DExplain!,
                isBan = d.DIsBan,
                name = d.DName!,
                time = d.DCreateTime.ToString()!,
                icon = d.DIcon!,
                dlv=d.DLv,
                children = Get_Children_Dept(d.DId, depts, users)
            }).ToList();
            return Result(1, "ok", new
            {
                data
            });
            //
        }
        /// <summary>
        /// 获取部门下的用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Dept_Users(Org_Request_Dto dto)
        {
            var depts = _org_IOC._sys_department_EFCore.QueryAll().ToList();
            var dutie = _org_IOC._sys_duties_EFCore.QueryAll().ToList();
            List<string> list = Get_Children_DeptID(depts, dto.id);//获取部门下的子级部门ID
            list.Add(dto.id);
            var iq = _login_IOC._sys_User_EFCore.QueryAll(out int total, dto.page, dto.limit,false, o => o.UCreateTime , d => list.Contains(d.UDept!));



            var data =await iq .Select(d => new User_Response_Dto
                {
                    id = d.UId,
                    name = d.UName!,
                    account = d.UAccount!,
                    dept = d.UDept!,
                    duties = d.UDuty!,
                    datetime = d.UCreateTime.ToString()!,
                    isActive = d.UIsActive,
                    isBan = d.UIsBan,
                    sex=d.UGender,
                }).ToListAsync();

            data.ForEach(d =>
            {
                d.dept = depts.Where(e => e.DId == d.dept).SingleOrDefault()?.DName!;
                d.duties = dutie.Where(e => e.DId == d.duties).SingleOrDefault()?.DName!;
            });
            return Result(1, "ok", new
            {
                total,
                data
            });
        }
        /// <summary>
        /// 修改部门禁用状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Users(string id)
        {
            var user = _login_IOC._sys_User_EFCore.QueryAll(d => d.UId == id).SingleOrDefault();

            if (user!.UIsBan == 0)
            {
                user.UIsBan = 1;
                _login_IOC._sys_User_EFCore.Update(user);
                var result = _login_IOC._sys_User_EFCore.SaveChanges();
                var depts = _org_IOC._sys_department_EFCore.QueryAll().ToList();
                var dutie = _org_IOC._sys_duties_EFCore.QueryAll().ToList();
                List<string> list = Get_Children_DeptID(depts, id);//获取部门下的子级部门ID
                list.Add(id);

                var data = await _login_IOC._sys_User_EFCore.QueryAll()
               .Select(d => new User_Response_Dto
               {
                   id = d.UId,
                   name = d.UName!,
                   account = d.UAccount!,
                   dept = d.UDept!,
                   duties = d.UDuty!,
                   datetime = d.UCreateTime.ToString()!,
                   isActive = d.UIsActive,
                   isBan = d.UIsBan,
               }).ToListAsync();

                data.ForEach(d =>
                {
                    d.dept = depts.Where(e => e.DId == d.dept).SingleOrDefault()?.DName!;
                    d.duties = dutie.Where(e => e.DId == d.duties).SingleOrDefault()?.DName!;
                });
                return Result(1, "ok", new
                {
                    data
                });
            }
            else if (user.UIsBan == 1)
            {
                user.UIsBan = 0;
                _login_IOC._sys_User_EFCore.Update(user);
                var result = _login_IOC._sys_User_EFCore.SaveChanges();
                var depts = _org_IOC._sys_department_EFCore.QueryAll().ToList();
                var dutie = _org_IOC._sys_duties_EFCore.QueryAll().ToList();
                List<string> list = Get_Children_DeptID(depts, id);//获取部门下的子级部门ID
                list.Add(id);

                var data = await _login_IOC._sys_User_EFCore.QueryAll()
               .Select(d => new User_Response_Dto
               {
                   id = d.UId,
                   name = d.UName!,
                   account = d.UAccount!,
                   dept = d.UDept!,
                   duties = d.UDuty!,
                   datetime = d.UCreateTime.ToString()!,
                   isActive = d.UIsActive,
                   isBan = d.UIsBan,
               }).ToListAsync();

                data.ForEach(d =>
                {
                    d.dept = depts.Where(e => e.DId == d.dept).SingleOrDefault()?.DName!;
                    d.duties = dutie.Where(e => e.DId == d.duties).SingleOrDefault()?.DName!;
                });
                return Result(1, "ok", new
                {
                    data
                });
            }
            return Result(-1);
        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Del(string id)
        {
            var iq=_org_IOC._sys_department_EFCore.QueryAll(d=>d.DId == id).Single();
            _org_IOC._sys_department_EFCore.Delete(iq);
            var result= _org_IOC._sys_department_EFCore.SaveChanges();
            return Result(result);
        }
        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Details(string id)
        {
            var depts = _org_IOC._sys_department_EFCore.QueryAll().ToList();
            var dutie = _org_IOC._sys_duties_EFCore.QueryAll().ToList();

            var data =await _login_IOC._sys_User_EFCore.QueryAll().Where(d => d.UId == id)
           .Select(d => new User_Response_Dto
           {
               id = d.UId,
               name = d.UName!,
               account = d.UAccount!,
               dept = d.UDept!,
               duties = d.UDuty!,
               datetime = d.UCreateTime.ToString()!,
               isActive = d.UIsActive,
               isBan = d.UIsBan,
               desc = d.UDesc!
           }).ToListAsync();

            data.ForEach(d =>
            {
                d.dept = depts.Where(e => e.DId == d.dept).SingleOrDefault()?.DName!;
                d.duties = dutie.Where(e => e.DId == d.duties).SingleOrDefault()?.DName!;
            });
            return Result(1, "ok", new
            {
                data
            });
        }
        /// <summary>
        /// 获取职务列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Duty(Org_Request_Dto dto)
        {
            var depts = await _org_IOC._sys_duties_EFCore.QueryAll(out int total, dto.page, dto.limit, false, d =>
              (dto.isBan == -1 || d.DIsBan == dto.isBan)
              ).ToListAsync();

            var root = depts.Where(d => d.DId == null).ToList();
            List<Duties_Response_Dto> data = new List<Duties_Response_Dto>();
            //获取各个职务的人数
            
            depts.ForEach(d =>
            {
                var users = _login_IOC._sys_User_EFCore.QueryAll(e => e.UDuty == d.DId).ToList();
                data.Add(new Duties_Response_Dto
                {
                    id = d.DId,
                    name = d.DName!,
                    Dlv = d.DLv,
                    CreateTime = d.DCreateTime.ToString()!,
                    isban = d.DIsBan,
                    Personnel = users.Count(),
                });
            });
            return Result(1, "ok", new
            {
                total,
                data
            });
        }
        /// <summary>
        /// 获取职务详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Personnel"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_DutyDetails(Org_Request_Dto dto)
        {

            var data = await _org_IOC._sys_duties_EFCore.QueryAll(out int total, dto.page, dto.limit, false, d => d.DId == dto.id)
           .Select(d => new Duties_Response_Dto
           {
               id = d.DId,
               name = d.DName!,
               Dlv = d.DLv,
               CreateTime = d.DCreateTime.ToString()!,
               isban = d.DIsBan,
               Dexplain = d.DExplain!,
           }).ToListAsync();

            return Result(1, "ok", new
            {
                data
            });
        }
        /// <summary>
        /// 获取部门子级ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<string> Get_Children_DeptID(List<SysDepartment> depts, string id)
        {
            List<string> ids = new List<string>();
            var  children = depts.Where(d => d.DParent == id).ToList();
            children.ForEach(d =>
            {
                ids.Add(d.DId);
                ids.AddRange(Get_Children_DeptID(depts, d.DId));
            });
            return  ids;
        }
        /// <summary>
        /// 获取子级部门
        /// </summary>
        /// <param name="dID"></param>
        /// <param name="depts"></param>
        /// <returns></returns>
        private IEnumerable<Department_Response_Dto> Get_Children_Dept(string dID, List<SysDepartment> depts, List<SysUser> users)
        {
            var root = depts.Where(d => d.DParent == dID).ToList();
            List<Department_Response_Dto> data = new List<Department_Response_Dto>();



            root.ForEach(d =>
            {
                data.Add(new Department_Response_Dto
                {
                    id = d.DId,
                    count = users.Count(e => e.UDept == d.DId),//users.Where(e=>e.UDeptID==d.DID).Count(),
                    explain = d.DExplain!,
                    isBan = d.DIsBan,
                    name = d.DName!,
                    time = d.DCreateTime.ToString()!,
                    icon = d.DIcon!,
                    children = Get_Children_Dept(d.DId, depts, users)
                });
            });
            return data;
        }
        public async Task<Api_Response_Dto> Add_User(string name, string account, string duty, string dept, string desc,string gender)
        {

            SysUser user = new SysUser()
            {
                UId = Config.GUID_1(),
                UAccount = account,
                UPassword = "1EC5D7A5B0EE2134F024FF3DC86C3C",
                UName = name,
                UDept = dept,
                UDuty = duty,
                UDesc = desc,
                UIsActive = 0,
                UIsBan = 0,
                UCreateTime = DateTime.Now,
                USalt = null,
                UGender=gender
            };
            //var data = _right_IOC._sys_right_config_org_EFCore.QueryAll(d => d.RcoDutyId == user.UDuty).ToList();
            //foreach (var a in data)
            //{
            //    var data2 = _right_IOC._sys_right_config_details_EFCore.QueryAll(d => d.RcdRcid == a.RcoRcid).ToList();
            //    foreach (var i in data2)
            //    {
            //        SysUserRight userRights = new SysUserRight()
            //        {
            //            UrId = Config.GUID_1(),
            //            UrUid = user.UId,
            //            UrRid = i.RcdRid,
            //            UrCreateTime = DateTime.Now,
            //        };
            //        _right_IOC._sys_user_rights_EFCore.Add(userRights);
            //    }
            //}
            //var result = _sys_UserRights_EF.SaveChanges();

            _login_IOC._sys_User_EFCore.Add(user);
            var result = _login_IOC._sys_User_EFCore.SaveChanges();
            return Result(result);
        }
        public async Task<Api_Response_Dto> Add_Dept(string name, int? lv, string desc)
        {
            SysDepartment sys_Department = new SysDepartment()
            {
                DId = Config.GUID_1(),
                DName = name,
                DParent = null,
                DCreateTime = DateTime.Now,
                DLv = Convert.ToInt32(lv),
                DIcon = null,
                DIsBan = 0,
                DExplain = desc
            };
           _org_IOC._sys_department_EFCore.Add(sys_Department);
            var result = _org_IOC._sys_department_EFCore.SaveChanges();
            return Result(result);
        }
        public async Task<Api_Response_Dto> Get_Dept(string id)
        {
            var depts = await _org_IOC._sys_department_EFCore.QueryAll(d =>
              d.DId==id).ToListAsync();
            //获取各个部门的人数
            var users = await  _login_IOC._sys_User_EFCore.QueryAll(d => d.UDept != null && d.UDept==id).ToListAsync();
            var data = depts.Select(d => new Department_Response_Dto
            {
                id = d.DId,
                count = users.Count(e => e.UDept == d.DId),
                explain = d.DExplain!,
                isBan = d.DIsBan,
                name = d.DName!,
                time = d.DCreateTime.ToString()!,
                icon = d.DIcon!,
                dlv = d.DLv
            }).ToList();
            return Result(1, "ok", new
            {
                data
            });
            //
        }

        public async Task<Api_Response_Dto> Add_Duty(string? name, int? dlv, string? explain)
        {
            SysDuty sysDuty = new SysDuty()
            {
                DId = Config.GUID_1(),
                DName = name,
                DLv = dlv,
                DCreateTime = DateTime.Now,
                DIsBan = 0,
                DExplain = explain
            };
            _org_IOC._sys_duties_EFCore.Add(sysDuty);
            var result = await _org_IOC._sys_duties_EFCore.SaveChangesAsync();
            return Result(result);
        }
        public async Task<Api_Response_Dto> Get_duty_xla()
        {
            var iq = _org_IOC._sys_duties_EFCore.QueryAll();
            var data = await iq.Select(d => new Dictionary_Type_Response_Dto
            {
                id = d.DId,
                name = d.DName,

            }).ToListAsync();


            return Result(1, "ok", new
            {
                data
            });
        }
        public async Task<Api_Response_Dto> Update_dept(string? id, string? name, int? dlv, string? explain)
        {
            var iq = _org_IOC._sys_department_EFCore.QueryAll(d => d.DId == id).Single();
            iq.DName = name;
            iq.DLv = dlv;
            iq.DExplain=explain;
            _org_IOC._sys_department_EFCore.Update(iq);
            var result = await _org_IOC._sys_department_EFCore.SaveChangesAsync();
            return Result(result);
        }
        public async Task<Api_Response_Dto> Update_Duty(string? id, string? name, int? dlv, string? explain,int? isBan)
        {
            var iq = _org_IOC._sys_duties_EFCore.QueryAll(d => d.DId == id).Single();
            iq.DName = name;
            iq.DLv = dlv;
            iq.DExplain = explain;
            iq.DIsBan = isBan;
            _org_IOC._sys_duties_EFCore.Update(iq);
            var result = await _org_IOC._sys_duties_EFCore.SaveChangesAsync();
            return Result(result);
        }
    }
}
